//
//  LGOAuthViewController.swift
//  LGWeibo
//
//  Created by 李更 on 8/10/16.
//  Copyright © 2016 itcast. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking

class LGOAuthViewController: UIViewController {
    override func loadView() {
        view = webView
        //判断url是否为nil

        guard let url = NSURL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(WBAppKey)&redirect_uri=\(WBRedirect_uri)") else{
            return
        }
        webView.delegate = self
        //实例化request
        let request = NSURLRequest(URL: url)
        //加载request
        
        webView.loadRequest(request)
        
        
    }
//    client_id	true	string	申请应用时分配的AppKey。
//    redirect_uri	true	string	授权回调地址，站外应用需与设置的回调地

    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()

    }
    
    //取消
    @objc private func cancelAction(){
        dismissViewControllerAnimated(false, completion: nil)
    }
    @objc private func autofillAction(){
        
        let jsString = "document.getElementById('userId').value='\(WBName)',document.getElementById('passwd').value='\(WBPasswd)'"
        webView.stringByEvaluatingJavaScriptFromString(jsString)
        
    }
    
   private func setupUI(){
        view.backgroundColor = UIColor.whiteColor()
        setupNav()
    }
    func setupNav(){
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "cancelAction")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autofillAction")
        navigationItem.title = "微博登录"
    }
    
    private lazy var webView : UIWebView = UIWebView()
    

}
extension LGOAuthViewController : UIWebViewDelegate {
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        if  let urlString = request.URL?.absoluteString where urlString.hasPrefix(WBRedirect_uri) {
           
                    if  let query = request.URL?.query {
                        let code = query.substringFromIndex("code=".endIndex)
                        LGUserAccountViewModel.sharedTools.getUserAccount(code, finish: { (isSuccess) in
                            if !isSuccess{
                                print("请求失败")
                                return
                            }
                            print("请求成功")
                            self.dismissViewControllerAnimated(false, completion: { 
                                
                                NSNotificationCenter.defaultCenter().postNotificationName(WBSWITCHROOTVCNOTIFICTION, object: "oauth")
                            })
                            
                        })
                    }
        }
         return true
    }
    
    //开始加载
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    //加载结束
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    //加载失败
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        
    }
    
    
}

extension LGOAuthViewController{
//    //获取授权
//    func getUserAccount(code : String){
//        HMNetworkTools.sharedTools.oauthLoadUserAccount(code, success: { (response) in
//            guard let res = response as? [String : AnyObject] else{
//                return
//            }
//            //          print("请求成功\(response)")
//            let userAccount = LGUserAccountModel(dict: res)
//            //        print(userAccount)
//            
//            self.getUserInfo(userAccount)
//            }) { (error) in
//                 print("请求失败\(error)")
//        }
//        
//        //请求urlstring
//        let urlString = "https://api.weibo.com/oauth2/access_token"
//        //请求参数
//        let params = [
//            "client_id" : WBAppKey,
//            "client_secret" : WBAppSecret,
//            " grant_type" : "authorization_code",
//            "code" : code,
//            "redirect_uri" : WBRedirect_uri
//            
//        ]
//        HMNetworkTools.sharedTools.request(HMNetworkToolsMethod.POST, urlString: urlString, parameters: params, success: { (response) in
//            guard let res = response as? [String : AnyObject] else{
//                return
//            }
//            //          print("请求成功\(response)")
//            let userAccount = LGUserAccountModel(dict: res)
//            //        print(userAccount)
//            
//            self.getUserInfo(userAccount)
//            }) { (error) in
//                   print("请求失败\(error)")
//        }
        
        
//        //发送请求
//        let manager = AFHTTPSessionManager()
//        //序列化类型
//        manager.responseSerializer.acceptableContentTypes?.insert("text/plain")
//       manager.POST(urlString, parameters: params, progress: nil, success: { (_, response) in
//        
//        guard let res = response as? [String : AnyObject] else{
//            return
//        }
////          print("请求成功\(response)")
//        let userAccount = LGUserAccountModel(dict: res)
////        print(userAccount)
//       
//        self.getUserInfo(userAccount)
//        
//        }) { (_, error) in
//            print("请求失败\(error)")
//        }
        
 
//    }
    
    
    
    
    
    
//    
//    func  getUserInfo(userAccount : LGUserAccountModel){
//        
//        HMNetworkTools.sharedTools.oauthloadUserInfo(userAccount, success: { (response) in
//            guard let res = response as? [String : AnyObject] else{
//                return
//            }
//            //赋值
//            userAccount.avatar_large = res["avatar_large"] as? String
//            userAccount.screen_name = res["screen_name"] as? String
//            
//            print(userAccount)
//            }) { (error) in
//                   print("请求失败\(error)")
//        }
//        //请求Urlstring
//        let urlString = "https://api.weibo.com/2/users/show.json"
//        //请求参数
//        let param = [
//            "access_token" : userAccount.access_token!,
//            "uid" : userAccount.uid!
//        ]
//        
//        
//        HMNetworkTools.sharedTools.request(HMNetworkToolsMethod.GET, urlString: urlString, parameters: param, success: { (response) in
//            guard let res = response as? [String : AnyObject] else{
//                return
//            }
//            //赋值
//            userAccount.avatar_large = res["avatar_large"] as? String
//            userAccount.screen_name = res["screen_name"] as? String
//            
//            print(userAccount)
//            }) { (error) in
//                 print("请求失败\(error)")
//        }
        
//        let manager = AFHTTPSessionManager()
//        
//        manager.GET(urlString, parameters: param, progress: nil, success: { (_, response) in
//             print("请求成功\(response)")
//            guard let res = response as? [String : AnyObject] else{
//                return
//            }
//            //赋值
//            userAccount.avatar_large = res["avatar_large"] as? String
//            userAccount.screen_name = res["screen_name"] as? String
//            
//            print(userAccount)
//            
//            }) { (_, error) in
//                    print("请求失败\(error)")
//        }
//    }
    
    
    
    
    
    
    
}








